package com.seley.gateway.zuul.filter;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.seley.gateway.zuul.feign.LoginFeignClient;

public class LoginFilter extends ZuulFilter {

	@Autowired
	private LoginFeignClient loginFeignClient;

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		
		String url = request.getRequestURI(); 
		if(url.startsWith("/loginSer/getToken")
				|| url.startsWith("/loginSer/checkToken")
				|| url.startsWith("/loginSer/reflashToken")) {
			return null;
		}
		
		String tokenstr = request.getHeader("Authorization");
		if(tokenstr == null) {
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(401);
			ctx.setResponseBody("{\"loginSuccess\":false}");
			return null;
		}
		
		boolean flag = loginFeignClient.validateJWT(tokenstr);
		if (flag) {
			ctx.setSendZuulResponse(true);
			ctx.setResponseStatusCode(200);
			return null;
		} else {
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(401);
			ctx.setResponseBody("{\"loginSuccess\":false}");
			return null;
		}

	}

	/**
	 * pre：可以在请求被路由之前调用 route：在路由请求时候被调用 post：在route和error过滤器之后被调用
	 * error：处理请求时发生错误时被调用
	 */
	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

}
